const mysql = require('mysql');
const connection = mysql.createConnection({
    host: '81.69.7.51',
    user: 'rootyyy',
    password: 'Yang1234',
    database: 'tododb'
});
connection.connect();

function addItem(data) {
    //userlist userid  ???
    var addSql = 'INSERT INTO todolist(id,title,completed) VALUES(?,?,?)';
    var addSqlParams = [data.id, data.title, data.completed];
    //增
    connection.query(addSql, addSqlParams)



    //更新缓存，

    //     ,function (err, result) {
    // connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
    //   if (error) throw error;
    //   console.log('The solution is: ', results[0].solution);
    // });

    // connection.end()

}

// function updateItem(data) {
//     //??  update where id=data.id
//     var delSql = 'update from todolist set id=?,title=?,completed=? where id=?';
//     var delSqlParams = [data.id, data.title, data.completed];
//     connection.query(delSql, delSqlParams)
//     let todo = await getTodoList()
//     return todo
// }

async function deleteItem(delid) {
    //??  update where id=data.id
    var delSql = 'delete from todolist where id=?';
    var delSqlParams = [delid];
    //增
    connection.query(delSql, delSqlParams)
    let todo = await getTodoList()
    return todo
}

async function getTodoList() {

    // 先去缓存里查找，有的话，直接从缓存读取，没有的话，从数据库读取，再存到缓存以便下次请求时使用
    const sql = "select * from todolist"

    const mypromise = new Promise((resolve, reject) => {

        connection.query(sql, function (err, result) {
            if (err) {
                reject(err)
                return;
            }

            resolve(result)
        })

    })

    const result = await mypromise
    const myarray = JSON.parse(JSON.stringify(result)) //RowDataPacket
    console.log(myarray);
    return myarray

    //存到缓存，后面从缓存里面获取
}

/*
async function addItem(data){

    const tlist=await getTodoList()

    tlist.push(data)

    const jstr=JSON.stringify(tlist)
    const key="todolist"
    client.set(key,jstr)
}*/


module.exports = {
    getTodoList,
    addItem,
    deleteItem,
    // updateItem
}